package com.yangchoi.lib_base.network.interceptor

import com.google.gson.Gson
import com.orhanobut.logger.Logger
import com.yangchoi.lib_base.base.BaseResult
import com.yangchoi.lib_base.network.ApiService
import com.yangchoi.lib_base.utils.LogUtil.showHttpApiLog
import com.yangchoi.lib_base.utils.LogUtil.showHttpHeaderLog
import com.yangchoi.lib_base.utils.LogUtil.showHttpLog
import okhttp3.Interceptor
import okhttp3.Request
import okhttp3.RequestBody
import okhttp3.Response
import okio.Buffer
import java.io.IOException
import java.net.URLDecoder
import java.nio.charset.Charset
import java.nio.charset.StandardCharsets
import kotlin.jvm.Throws

/**
 * Created on 2021/4/27
 * describe:
 */
class LoggingInterceptor : Interceptor {
    @Throws(IOException::class)
    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()
        val httpUrl = request.url
        val t1 = System.nanoTime() //请求发起的时间
        val response = chain.proceed(request)
        val t2 = System.nanoTime() //收到响应的时间
        val responseBody = response.peekBody(1024 * 1024.toLong())
        if (httpUrl.toString().contains(".png")
            || httpUrl.toString().contains(".jpg")
            || httpUrl.toString().contains(".jpeg")
            || httpUrl.toString().contains(".gif")
        ) {
            return response
        }

        var api = httpUrl.toString().replace(ApiService.Base_Url, "")
        if (api.contains("?")) {
            api = api.substring(0, api.indexOf("?"))
        }
        val result = responseBody.string()
//        val baseResult = Gson().fromJson(result, BaseResult::class.java)

        logRequestInfo(request,response,result)

        // 拦截出错一些操作,比如toast提示用户
//        if(baseResult.errorCode != 0){
//            ToastUtils.showShort(baseResult.msg)
//        }

        return response
    }

    private fun logRequestInfo(request: Request, response: Response, result:String){
        Logger.d("\n\n请求地址===>${request.toString()}  \n" +
                "request请求头===>${request.headers.toString()} \n"+
                "response请求头===>${response.headers.toString()} \n"+
                "数据格式===>${response.body?.contentType()} \n" +
                "请求参数===>${printParams(request.body)} \n" +
                "请求结果===>${result} \n\n")
    }

    private fun printParams(body: RequestBody?):String {
        val buffer = Buffer()
        return try {
            body?.writeTo(buffer)
            var charset = Charset.forName("UTF-8")
            val contentType = body?.contentType()
            if (contentType != null) {
                charset = contentType.charset(StandardCharsets.UTF_8)
            }
            buffer.readString(charset!!)
        } catch (e: IOException) {
            e.printStackTrace()
            ""
        }
    }
}